<?php
class WebServiceServer {
	private $key;
	private $version;

	public function __construct($key, $version) {
		$this->key = $key;
		$this->version = $version;
	}

	protected function extractVersion($version) {
		$tmp = explode(".", $version);
		$tmp[0] = isset($tmp[0]) ? (int) $tmp[0] : 0;
		$tmp[1] = isset($tmp[1]) ? (int) $tmp[1] : 0;
		$tmp[2] = isset($tmp[2]) ? (int) $tmp[2] : 0;

		return $tmp;
	}

	protected function checkSignature($num_files, $function_name, $parameters, $signature) {
		$good_signature = sha1($this->key . $num_files . $function_name . $parameters);

		if ($good_signature == $signature) {
			return TRUE;
		}
		return FALSE;
	}

	protected function checkVersion($client_version) {
		if ( ($client_version != '0.0.0') ) {
			list($cx, $cy, $cz) = $this->extractVersion($client_version);
			list($sx, $sy, $sz) = $this->extractVersion($this->version);

			if ( ($sx != $cx) || ($sy < $cy) ) {
				return FALSE;
			}
		}

		return TRUE;
	}

	protected function handleRequest($function_name, $parameters, $files) {
		return call_user_func_array($function_name, $parameters); 
	}

	public function process() {
		$function_name = $_REQUEST['function_name'];
		$parameters = $_REQUEST['parameters'];
		$signature = $_REQUEST['signature'];
		$client_version = isset($_REQUEST['version']) ? $_REQUEST['version'] : '0.0.0';
		$num_files = sizeof($_FILES) ? (sizeof($_FILES['file']['name'])) : 0;

		$ret = $this->checkSignature($num_files, $function_name, $parameters, $signature);
		if (!$ret) {
			http_send_status(405);
			exit();
		}

		$ret = $this->checkVersion($client_version);
		if (!$ret) {
			http_send_status(406);
			exit();
		}

		$parameters = json_decode($parameters, TRUE);
		$response = $this->handleRequest($function_name, $parameters, $_FILES);

		echo json_encode($response);
	}
}
?>
